package com.atguigu.spzx.cart.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.atguigu.product.feign.ProductFeignClient;
import com.atguigu.spzx.cart.service.CartService;
import com.atguigu.spzx.model.pojo.h5.CartInfo;
import com.atguigu.spzx.model.pojo.h5.UserInfo;
import com.atguigu.spzx.model.pojo.h5.UserInfoAuthContextUtil;
import com.atguigu.spzx.model.pojo.product.ProductSku;
import com.atguigu.spzx.model.vo.common.Result;
import com.atguigu.spzx.utils.DYLAssert;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.Date;
import java.util.List;


/**
 * 类名称：CartServiceImpl
 * 描述： 购物车服务service
 * 创建人: 17605
 * 创建时间: 2025/01/27
 */
@Service
public class CartServiceImpl implements CartService {
    @Autowired
    private ProductFeignClient productFeignClient;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    /**
     * @param skuId
     * @param skuNum
     * @doc: 添加购物车
     * @author 17605
     * @date 2025/01/27
     */
    @Override
    public void addToCart(Long skuId, Integer skuNum) {
        // 获取当前用户
        UserInfo userInfo = UserInfoAuthContextUtil.get();
        // redis中的key
        String key = "user:cart:" + userInfo.getId();
        // 1、先查询商品sku，然后存入redis中
        Result<ProductSku> bySkuId = productFeignClient.getBySkuId(skuId);
        ProductSku productSku = bySkuId.getData();
        // 1.1 存redis之前先查询是否有该商品
        Object o = redisTemplate.opsForHash().get(key, String.valueOf(skuId));
        // 存在该商品，则加数量
        CartInfo cartInfo = null;
        if (o != null) {
            cartInfo = JSON.parseObject(o.toString(), CartInfo.class);
            cartInfo.setSkuNum(cartInfo.getSkuNum() + skuNum);
            cartInfo.setIsChecked(0);
            cartInfo.setUpdateTime(new Date());
        }
        // 不存在，就存入redis
        else {
            cartInfo = new CartInfo();
            cartInfo.setCartPrice(productSku.getSalePrice());
            cartInfo.setIsChecked(0);
            cartInfo.setSkuName(productSku.getSkuName());
            cartInfo.setSkuId(productSku.getId());
            cartInfo.setImgUrl(productSku.getThumbImg());
            cartInfo.setSkuNum(skuNum);
            cartInfo.setUserId(userInfo.getId());
            cartInfo.setCreateTime(new Date());
            cartInfo.setUpdateTime(new Date());
        }
        // 序列化之后存入redis
        String jsonString = JSON.toJSONString(cartInfo, SerializerFeature.BrowserSecure);
        redisTemplate.opsForHash().put(key, String.valueOf(productSku.getId()), jsonString);
    }


    /**
     * @doc: 获取购物车列表
     * @return: List
     * @author 17605
     * @date 2025/01/27
     */
    @Override
    public List<CartInfo> getCartList() {
        // 获取当前用户
        UserInfo userInfo = UserInfoAuthContextUtil.get();
        // redis中的key
        String key = "user:cart:" + userInfo.getId();
        // 获取数据
        List<Object> cartInfoList = redisTemplate.opsForHash().values(key);
        List<CartInfo> cartInfos = new ArrayList<>();
        if (!CollectionUtils.isEmpty(cartInfoList)) {
//            List<CartInfo> infoList = cartInfoList.stream().map(cartInfoJSON -> JSON.parseObject(cartInfoJSON.toString(), CartInfo.class))
//                    .sorted((o1, o2) -> o2.getCreateTime().compareTo(o1.getCreateTime()))
//                    .collect(Collectors.toList());
            for (Object o : cartInfoList) {
                CartInfo cartInfo = JSON.parseObject(o.toString(), CartInfo.class);
                cartInfos.add(cartInfo);
            }
//            按时间进行排序
            cartInfos.sort(new Comparator<CartInfo>() {
                @Override
                public int compare(CartInfo o1, CartInfo o2) {
                    return o2.getCreateTime().compareTo(o1.getCreateTime());
                }
            });
        }
        return cartInfos;
    }

    /**
     * @doc: 删除购物车选项
     * @params: @param skuId
     * @return: @return boolean
     * @author 17605
     * @date 2025/01/27
     */
    @Override
    public boolean deleteCartItem(Integer skuId) {
        // 获取当前用户
        UserInfo userInfo = UserInfoAuthContextUtil.get();
        // redis中的key
        String key = "user:cart:" + userInfo.getId();
        return redisTemplate.opsForHash().delete(key, skuId.toString()) > 0;
    }

    /**
     * @param skuId
     * @param isChecked
     * @doc: 勾选购物车选项
     * @author 17605
     * @date 2025/01/27
     */
    @Override
    public void checkCart(Integer skuId, Integer isChecked) {
        // 获取当前用户
        UserInfo userInfo = UserInfoAuthContextUtil.get();
        // redis中的key
        String key = "user:cart:" + userInfo.getId();
        Object o = redisTemplate.opsForHash().get(key, skuId.toString());
        DYLAssert.notNull(o, "购物车商品为空");
        // 获取商品对象
        CartInfo cartInfo = JSON.parseObject(o.toString(), CartInfo.class);
        // 更新商品对象
        cartInfo.setIsChecked(isChecked);
        // 存入redis
        redisTemplate.opsForHash().put(key, skuId.toString(), JSON.toJSONString(cartInfo));
    }

    /**
     * @param isChecked
     * @return boolean
     * @doc: 勾选所有购物车选项
     * @author 17605
     * @date 2025/01/27
     */
    @Override
    public boolean checkAllCart(Integer isChecked) {
        // 获取当前用户
        UserInfo userInfo = UserInfoAuthContextUtil.get();
        // redis中的key
        String key = "user:cart:" + userInfo.getId();
        // 获取所有购物车
        List<Object> values = redisTemplate.opsForHash().values(key);
        // 清空之前的redis记录
        //KEYPOINT redis中遵循覆盖原则
        for (Object o : values) {
            // 重新存入新的redis
            CartInfo cartInfo = JSON.parseObject(o.toString(), CartInfo.class);
            cartInfo.setIsChecked(isChecked);
            redisTemplate.opsForHash().put(key,cartInfo.getSkuId().toString(),JSON.toJSONString(cartInfo,SerializerFeature.BrowserSecure));
        }
        return true;
    }


    /**
     * @doc: 清空购物车
     * @author 17605
     * @date 2025/01/27
     */
    @Override
    public void clearCart() {
        // 获取当前用户
        UserInfo userInfo = UserInfoAuthContextUtil.get();
        // redis中的key
        String key = "user:cart:" + userInfo.getId();
        // 删除redis中的key值
        Boolean delete = redisTemplate.delete(key);
        DYLAssert.isTrue(delete,"删除失败");
    }

    @Override
    public List<CartInfo> getAllChecked() {
        // 获取当前用户
        UserInfo userInfo = UserInfoAuthContextUtil.get();
        // redis中的key
        String key = "user:cart:" + userInfo.getId();
        List<Object> values = redisTemplate.opsForHash().values(key);
        List<CartInfo> cartInfoList = new ArrayList<>();
        for (Object value : values) {
            CartInfo cartInfo = JSON.parseObject(value.toString(), CartInfo.class);
            if (cartInfo.getIsChecked() == 1){
                cartInfoList.add(cartInfo);
            }
        }
        return cartInfoList;
    }
}
